#ifndef _HJ212_PACK_H
#define _HJ212_PACK_H

#include <time.h>

#include "hj212_client_def.h"
#include <stdarg.h>

#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif

#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif

enum hj212_unpack_checkflag
{
    UNPACK_NO_CHECK_CRC = (1 << 0),         // 忽略CRC
    UNPACK_NO_CHECK_DATALEN = (1 << 1),     // 忽略包长度
};
enum hj212_unpack_result
{
    UNPACK_NORMAL       = 0,
    UNPACK_NO_HEAD      = (1 << 0),
    UNPACK_NO_END       = (1 << 1),
    UNPACK_LEN_ERROR    = (1 << 2),
    UNPACK_CRC_ERROR    = (1 << 3),
    UNPACK_NO_QN        = (1 << 4),
    UNPACK_NO_ST        = (1 << 5),
    UNPACK_NO_CN        = (1 << 6),
    UNPACK_NO_PW        = (1 << 7),
    UNPACK_NO_MN        = (1 << 8),
    UNPACK_NO_FLAG      = (1 << 9),
    UNPACK_NO_CP        = (1 << 10),
};

unsigned int HJ212_CRC16(const char *buf, int len);

void hj212_generate_qn(char *buffer, int bufferlen, struct timeval precise_time);
void hj212_pack_head_pnum(const char *qn, const char *sys_code,
                          int cn, const char *access_pwd,
                          const char *mn, int flag,
                          int pnum, int pno,
                          char *buffer, int bufferlen);
void hj212_pack_head(const char *qn, const char *sys_code,
                     int cn, const char *access_pwd,
                     const char *mn, int flag,
                     char *buffer, int bufferlen);
void hj212_pack_datatime(char *buffer, int bufferlen, time_t datatime);
void hj212_pack_rtdata(char *buffer, int bufferlen, const struct pol_rtval *pol);
void hj212_pack_hisdata(char *buffer, int bufferlen, const struct pol_his_data *pol);
void hj212_pack_end(char *buffer, int bufferlen);
int hj212_pack_add_field(char *buffer, int bufferlen, const char *format, ...);
uint32_t hj212_unpack(const char *buffer, int bufferlen, struct hj212_generalmsg *msg, int checkmark, const char **next);

int hj212_unpack_string(const char *package, const char *keyword, const char *end, char *result, int result_maxlen);
int hj212_unpack_int(const char *package, const char *keyword, const char *end, int *result);


int _hj212_pack_add_field(char *buffer, int bufferlen, const char *format, va_list ap);



#endif
